#!/usr/bin/env Python
# coding=utf-8
import pymysql
import pymysql.cursors
from .Fields import Field
from .logHelper import logger

class baseQuery(object):
    def __init__(self, db=None , modelInfo=None):
        if not db == None:
            self.db = db

        if not modelInfo == None:
            self.modelInfo=modelInfo

    def __conn__(self,dbase):
        return pymysql.connect(**dbase)


    def ExecuteFetchall(self, query=None ,args=None):
        #logger.info("sql->%s;args->%s" % (query, args))
        conn = self.__conn__(self.db)
        with conn.cursor(cursor=pymysql.cursors.DictCursor) as cur:
            cur.execute(self.modelInfo.select(query),args);
            #cur.execute(query,args)
            lines = cur.fetchall()
            cur.close()  # 关闭光标对象
            conn.close()  # 关闭数据库连接
            return [self.modelInfo(**r) for r in lines]

    def ExecuteFetchone(self, query=None,args=None):
        #logger.info("sql->%s;args->%s" % (query,args))
        conn = self.__conn__(self.db)
        with conn.cursor(cursor=pymysql.cursors.DictCursor) as cur:
            #cur.execute(self.modelInfo.selectInfo(query), args);
            cur.execute(query,args);
            rs = cur.fetchone()
            cur.close()  # 关闭光标对象
            conn.close()  # 关闭数据库连接
            if rs is None:
                return None
            return self.modelInfo(**rs)

    def Execute(self, query=None,ages=None):
        conn = self.__conn__(self.db)
        with conn.cursor(cursor=pymysql.cursors.DictCursor) as cur:
            cur.execute(query,ages)
            conn.commit()
            row = self.modelInfo(**cur.rowcount)
            cur.close()
            return row

